
package com.rt.schedulenew.utils.coder;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

public abstract class DESCoder extends SecurityCoder
{
    public static final String KEY_ALGORITHM = "DES";
    public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";
    
    private static Key toKey(final byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
        final DESKeySpec dks = new DESKeySpec(key);
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        final SecretKey secretKey = keyFactory.generateSecret(dks);
        return secretKey;
    }
    
    public static byte[] decrypt(final byte[] data, final byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        final Key k = toKey(key);
        final Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5PADDING");
        cipher.init(2, k);
        return cipher.doFinal(data);
    }
    
    public static byte[] encrypt(final byte[] data, final byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {
        final Key k = toKey(key);
        final Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5PADDING");
        cipher.init(1, k);
        return cipher.doFinal(data);
    }
    
    public static byte[] initKey() throws NoSuchAlgorithmException {
        final KeyGenerator kg = KeyGenerator.getInstance("DES");
        kg.init(56, new SecureRandom());
        final SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }
}
